package config

import (
	"log"
	"os"
	"strconv"
	"time"
)

// Config 应用配置结构
type Config struct {
	// 服务器配置
	Server ServerConfig `json:"server"`
	// 健康检查配置
	HealthCheck HealthCheckConfig `json:"health_check"`
	// 日志配置
	Log LogConfig `json:"log"`
	// 持久化配置
	Persistence PersistenceConfig `json:"persistence"`
}

// ServerConfig 服务器配置
type ServerConfig struct {
	Port         int           `json:"port"`
	Host         string        `json:"host"`
	ReadTimeout  time.Duration `json:"read_timeout"`
	WriteTimeout time.Duration `json:"write_timeout"`
}

// HealthCheckConfig 健康检查配置
type HealthCheckConfig struct {
	// 健康检查间隔（秒）
	Interval int `json:"interval"`
	// 实例不健康阈值（秒）
	UnhealthyThreshold int `json:"unhealthy_threshold"`
	// 实例删除阈值（秒）
	RemoveThreshold int `json:"remove_threshold"`
}

// LogConfig 日志配置
type LogConfig struct {
	Level  string `json:"level"`
	Format string `json:"format"`
}

// PersistenceConfig 持久化配置
type PersistenceConfig struct {
	Enabled   bool          `json:"enabled"`
	DataDir   string        `json:"data_dir"`
	BackupDir string        `json:"backup_dir"`
	Interval  time.Duration `json:"interval"`
}

var globalConfig *Config

// InitConfig 初始化配置
func InitConfig() *Config {
	if globalConfig != nil {
		return globalConfig
	}

	globalConfig = &Config{
		Server: ServerConfig{
			Port:         getEnvAsInt("SERVER_PORT", 9898),
			Host:         getEnv("SERVER_HOST", "0.0.0.0"),
			ReadTimeout:  time.Duration(getEnvAsInt("SERVER_READ_TIMEOUT", 30)) * time.Second,
			WriteTimeout: time.Duration(getEnvAsInt("SERVER_WRITE_TIMEOUT", 30)) * time.Second,
		},
		HealthCheck: HealthCheckConfig{
			Interval:           getEnvAsInt("HEALTH_CHECK_INTERVAL", 15),
			UnhealthyThreshold: getEnvAsInt("HEALTH_CHECK_UNHEALTHY_THRESHOLD", 15),
			RemoveThreshold:    getEnvAsInt("HEALTH_CHECK_REMOVE_THRESHOLD", 30),
		},
		Log: LogConfig{
			Level:  getEnv("LOG_LEVEL", "info"),
			Format: getEnv("LOG_FORMAT", "text"),
		},
		Persistence: PersistenceConfig{
			Enabled:   getEnv("PERSISTENCE_ENABLED", "true") == "true",
			DataDir:   getEnv("PERSISTENCE_DATA_DIR", "./data"),
			BackupDir: getEnv("PERSISTENCE_BACKUP_DIR", "./data/backup"),
			Interval:  time.Duration(getEnvAsInt("PERSISTENCE_INTERVAL", 30)) * time.Second,
		},
	}

	log.Printf("Configuration initialized: Server Port=%d, Health Check Interval=%ds",
		globalConfig.Server.Port, globalConfig.HealthCheck.Interval)

	return globalConfig
}

// GetConfig 获取全局配置
func GetConfig() *Config {
	if globalConfig == nil {
		return InitConfig()
	}
	return globalConfig
}

// getEnv 获取环境变量，如果不存在则返回默认值
func getEnv(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

// getEnvAsInt 获取环境变量并转换为int，如果不存在或转换失败则返回默认值
func getEnvAsInt(key string, defaultValue int) int {
	if value := os.Getenv(key); value != "" {
		if intValue, err := strconv.Atoi(value); err == nil {
			return intValue
		}
		log.Printf("Warning: Invalid integer value for %s: %s, using default %d", key, value, defaultValue)
	}
	return defaultValue
}
